package com.ydj.framework.interceptor;

import com.google.common.util.concurrent.RateLimiter;
import com.ydj.framework.exception.RateLimiterException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

/**
 * 限流的拦截器
 */
public class RateLimitInterceptor extends BaseInterceptor {
    private static final RateLimiter rateLimiter = RateLimiter.create(500);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws RateLimiterException {
        if (rateLimiter.tryAcquire(Duration.ofSeconds(5))) {
            return true;
        }
        throw new RateLimiterException();
    }
}